#!/bin/bash

# 配置kubeconfig
Configure_kubeconfig (){
[[ -d /tmp/api ]] || mkdir /tmp/api
cd /tmp/api/
## user
openssl req -new -newkey rsa:2048 -nodes -keyout api.key -out api.csr -subj "/CN=api"  &> /dev/null 
openssl x509 -req -in api.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out api.crt -days 365 &> /dev/null
kubectl config set-credentials api --client-certificate api.crt --client-key api.key --embed-certs=true --kubeconfig=./config &> /dev/null
## cluster
kubectl config set-cluster cks --kubeconfig ./config --server="https://127.0.0.1:6443" --certificate-authority=/etc/kubernetes/pki/ca.crt &> /dev/null
## context
kubectl config set-context api@cks --cluster=cks --user=api --kubeconfig ./config &> /dev/null
kubectl config use-context api@cks --kubeconfig ./config &> /dev/null
## privileges
kubectl create clusterrolebinding system:anonymous --clusterrole=cluster-admin --user=api &> /dev/null
## 替换config
cat ./config > ~/.kube/config
## 删除临时文件
rm -rf /tmp/api
}

# 主函数
main (){
	Configure_kubeconfig

	sleep 2
	echo -e "\033[32m==================> api config Done.\033[0m"
}

